import qs from 'qs'

const BASE_URL = 'https://api.huhuiyu.top'
const TOKEN_KEY = BASE_URL + '_token_info'

const tokenInfo = {
	save: (data) => {
		if (data && data.token) {
			uni.setStorageSync(TOKEN_KEY, data.token)
		}
	},
	load: () => {
		let token = uni.getStorageSync(TOKEN_KEY)
		return token ? token : ""
	},
	remove: () => {
		uni.removeStorageSync(TOKEN_KEY)
	}
}

const ApiService = {
	/**
	 * 转换json到查询字符串
	 * @param obj json对象
	 * @return json对应的查询字符串
	 */
	get_url_params: (obj) => {
		return qs.stringify(obj)
	},
	send: (url, params, cb, method) => {
		uni.request({
			url: BASE_URL + url,
			method: method,
			data: params,
			header: {
				'content-type': 'application/json',
				Authorization: tokenInfo.load()
			},
			success: (resp) => {
				tokenInfo.save(resp.data)
				cb(resp.data)
			},
			fail: (error) => {
				console.error('请求失败', error)
				cb({
					success: false,
					code: 500,
					message: "出bug了"

				})
			},

		})
	},
	get: (url, params, cb) => {
		ApiService.send(url, params, cb, "GET")
	},
	post: (url, params, cb) => {
		ApiService.send(url, params, cb, "POST")
	},
	put: (url, params, cb) => {
		ApiService.send(url, params, cb, "PUT")
	},
	delete: (url, params, cb) => {
		ApiService.send(url, params, cb, "DELETE")
	},
	patch: (url, params, cb) => {
		ApiService.send(url, params, cb, "PATCH")
	},
}

export default ApiService

export {
	ApiService as ApiService
}